<script lang="ts" setup>
import { type AfterFetchContext } from '@vueuse/core'
import type { IBasic } from '~/types/apis/basic'

const formModel = defineModel<Record<string, any>>('formModel', {
  required: true,
})
const emits = defineEmits<{
  (e: 'deserialize'): void
}>()

const props = withDefaults(
  defineProps<{
    caseType?: 'ui' | 'api' | 'mix' | 'before' | 'stress'
  }>(), {}
)

const route = useRoute()
const router = useRouter()
const { setEditState } = useTemporaryStore()
const { selectedModuleId, editState } = storeToRefs(useTemporaryStore())
const globalConfig = useGlobalConfigStore()


const isEditState = computed(() => route.fullPath.includes('is-edit=true'))

onMounted(() => {
  if ((!selectedModuleId.value || selectedModuleId.value === -1) && props.caseType !== 'before') {
    // eslint-disable-next-line unicorn/prefer-at
    router.push(route.matched[route.matched.length - 2])
  }
  if (!editState.value != null) {
    if (props.caseType === 'stress') {
      fetchStressCaseFind().execute()
    } else {
      formModel.value = {
        ...formModel.value,
        ...editState.value,
      }
      emits('deserialize')
      setEditState(null)
    }



  }
  nextTick(() => {
    formModel.value.moduleId = selectedModuleId.value!
  })
})




const { post: fetchStressCaseFind } = useCustomFetch(
  `/engine-service/api/v1/stress_case/find?projectId=${globalConfig.config.projectId}&id=${route.query.id}`,
  {
    immediate: false,
    afterFetch(ctx: AfterFetchContext<IBasic>) {
      if (ctx.data && ctx.data.code === 0) {
        const res = ctx.data.data
        formModel.value = { ...formModel.value, ...res }
        emits('deserialize')
        setEditState(null)
      }
      return ctx
    },
  },
)

defineExpose({
  isEditState,
})
</script>

<template>
  <slot />
</template>
